﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PMCSerialTransfer.Packets 
{
    public class RecvDataPacket : APacket
    {
        public override bool Packet(byte[] Data)
        {
            return Process(Data);
        }

        public override bool EndProcess(bool Ok)
        {
            if (Ok)
            {
                Globals.Message = ".";
                Globals.PacketSize = Globals.DataPacket.Length;
                Globals.FileStream.Write(Globals.DataPacket, 0, Globals.DataPacket.Length);
                Globals.FilePtr += Globals.DataPacket.Length;
                Globals.ProgressEvent = Globals.ProgressType.Add;
                if (Globals.FilePtr >= Globals.FileLen)
                {
                    Globals.FileStream.Close();
                    Globals.Message += "\nFile Received\n";
                    Globals.ProgressEvent = Globals.ProgressType.Clear;
                }
                ACKPacket(Globals.ACKType.E_ACK);
            }
            else
            {
                Globals.ErrorCount++;
                if (Globals.ErrorCount < 10)
                {
                    ACKPacket(Globals.ACKType.E_ERR);
                    Globals.Message = "CRC Error... Retrying\n";
                }
                else
                {
                    ACKPacket(Globals.ACKType.E_ABORT);
                    Globals.Message = "Transmission Error... Aborting\n";
                    Globals.FileStream.Close();
                    File.Delete(Globals.FileStream.Name);
                    Globals.ErrorCount = 0;
                }
            }
            return Ok;
        }
    }
}
